<template>
  <div class="app-container">
    <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item size="mini" label="" prop="ruleConfigName">
        <el-input
          v-model="queryParams.ruleConfigName"
          placeholder="规则名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item size="mini">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>

      <el-form-item size="mini">
        <el-button
          v-hasPermi="['system:ruleConfig:add']"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" size="small" :data="ruleConfigList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="规则名称" align="left" min-width="100px" prop="ruleConfigName"/>
      <el-table-column label="模板标题" align="left" min-width="200px" prop="templateTitle"/>
      <el-table-column label="执行方法" align="center" width="200px" prop="ruleConfigExecFunction"/>
      <el-table-column label="执行频率" align="center" width="80px" prop="ruleConfigExecFrequency"
                       :formatter="ruleConfigExecFrequencyFormat"/>
      <el-table-column label="执行阈值" align="center" width="80px" prop="ruleConfigThreshold"/>
      <el-table-column label="状态" align="center" :formatter="isValidFormat">
        <el-tag slot-scope="{ row }" size="small" :type="row.isValid ? 'primary' : 'info'">{{
            row.isValid ? '有效' : '无效'
          }}
        </el-tag>
      </el-table-column>
      <el-table-column label="操作" align="center" width="220px" class-name="small-padding fixed-width">
        <template slot-scope="{ row }">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(row)"
                     v-hasPermi="['system:ruleConfig:edit']">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(row)"
                     v-hasPermi="['system:ruleConfig:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="title" :visible.sync="open" :close-on-click-modal="false" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="规则名称" prop="ruleConfigName">
              <el-input v-model.trim="form.ruleConfigName" placeholder="请输入规则名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规则类型" prop="ruleConfigType">
              <el-select v-model="form.ruleConfigType" placeholder="请选择">
                <el-option
                  v-for="dict in ruleConfigTypeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="ruleConfigExecFrequency">
              <span slot="label">规则执行频次
              <el-tooltip class="item" effect="dark" placement="top">
                <div slot="content" style="white-space: pre-line">{{ tooltipContent }}</div>
                <i class="el-icon-question rule-content"/>
              </el-tooltip>
              </span>
              <el-select v-model="form.ruleConfigExecFrequency" placeholder="请选择">
                <el-option
                  v-for="dict in ruleConfigExecFrequencyOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>

          </el-col>
          <el-col :span="12">
            <el-form-item label="偏移量" prop="ruleConfigThreshold">
              <el-input v-model.trim="form.ruleConfigThreshold" placeholder="请输入偏移量"/>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="规则执行方法" prop="ruleConfigExecFunction">
              <el-select v-model="form.ruleConfigExecFunction"
                         style="width: 100%"
                         placeholder="请选择规则执行方法">
                <el-option
                  v-for="dict in ruleConfigExecFunctionOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="规则执行参数" prop="ruleConfigExecParameter">
              <el-input v-model.trim="form.ruleConfigExecParameter" type="textarea" :autosize="{minRows : 3 ,maxRows : 10}" placeholder="请输入规则执行参数"/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="延迟时间" prop="execOffset">
              <el-input v-model="form.execOffset" placeholder="消息延迟时间"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="延迟单位" prop="execOffsetField">
              <el-select v-model="form.execOffsetField" placeholder="请选择延迟单位">
                <el-option
                  v-for="dict in execOffsetFieldOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="接收人员" prop="sysSenderList">
              <el-input class="fake-selector" readonly :value="showUserNames" auto-complete="off" placeholder="请选择接收人员"
                        @click.native="showSelectUser = true">
                <i slot="append" class="el-icon-arrow-down"/>
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="接收角色" prop="ruleConfigSenderRole">
              <el-select v-model="ruleConfigSenderRoleList"
                         clearable
                         filterable
                         multiple
                         style="width: 100%"
                         placeholder="请选择消息接收的角色">
                <el-option
                  v-for="role in roleList"
                  :key="role.roleId"
                  :label="role.roleName"
                  :value="role.roleId.toString()"
                  :disabled="role.status == 1"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="isValid">
              <el-radio-group v-model="form.isValid" size="small">
                <el-radio-button label="1">有效</el-radio-button>
                <el-radio-button label="0">无效</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否发送通知" prop="isValid">
              <el-radio-group v-model="form.isSendNotification" size="small">
                <el-radio-button label="1">发送</el-radio-button>
                <el-radio-button label="0">不发送</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="模板标题" prop="templateTitle">
              <el-input v-model.trim="form.templateTitle" placeholder="请输入模板标题" maxlength="50" show-word-limit/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="模板内容" prop="templateContent">
              <el-input v-model.trim="form.templateContent" type="textarea" :autosize="{minRows : 2 ,maxRows : 5}" placeholder="请输入模板内容"
                        maxlength="255" show-word-limit/>
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="open = false">取 消</el-button>
      </div>
      <select-user-dialog :show.sync="showSelectUser" :selected="selectedUser" multi :max-num="100"
                          @select="selectUserCallback"/>
    </el-dialog>
  </div>
</template>

<script>
import {getRuleConfig, listRuleConfig, saveRuleConfig, editRuleConfig, delRuleConfig} from '@/api/system/ruleConfig'
import {listRole} from "@/api/system/role";
import {listUser} from "@/api/system/user";
import SelectUserDialog from '@/views/components/SelectUserDialog'


export default {
  name: "ruleConfig",
  components: {SelectUserDialog},

  data() {
    return {
      ruleConfigSenderRoleList: [],
      // 遮罩层
      loading: false,
      //消息列表
      ruleConfigList: [],
      // 选中数组
      ruleConfigIds: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      //消息数据量
      total: 0,
      //规则执行频率
      ruleConfigExecFrequencyOptions: [],
      //规则执行方法
      ruleConfigExecFunctionOptions: [],
      //规则类型字典
      ruleConfigTypeOptions: [],
      //发送规则偏移单位
      execOffsetFieldOptions: [
        {'dictLabel': '分钟', 'dictValue': 'MINUTES'},
        {'dictLabel': '小时', 'dictValue': 'HOURS'},
        {'dictLabel': '天', 'dictValue': 'DAYS'}
      ],
      //弹窗标题
      title: '',
      //规则配置窗口是否打开
      open: false,
      //表单参数
      form: {},
      // 表单校验
      rules: {
        ruleConfigName: [
          {required: true, message: '规则配置名称不能为空', trigger: 'blur'}
        ],
        ruleConfigType: [
          {required: true, message: '规则类型不能为空', trigger: 'blur'}
        ],
        ruleConfigExecFrequency: [
          {required: true, message: '规则执行频次不能为空', trigger: 'blur'}
        ],
        ruleConfigThreshold: [
          {required: true, message: '规则执行偏移量不能为空', trigger: 'blur'}
        ],
        ruleConfigExecFunction: [
          {required: true, message: '规则执行方法不能为空', trigger: 'blur'}
        ],
        execOffset: [
          {required: true, message: '规则延迟时间不能为空', trigger: 'blur'}
        ],
        execOffsetField: [
          {required: true, message: '规则延迟单位不能为空', trigger: 'blur'}
        ],
        templateTitle: [
          {required: true, message: '模板标题不能为空', trigger: 'blur'}
        ],
        templateContent: [
          {required: true, message: '模板内容不能为空', trigger: 'blur'}
        ]
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ruleConfigName: undefined
      },
      roleList: [],
      userList: [],
      userParams: {
        pageNum: 1,
        pageSize: 10,
        ruleConfigName: undefined
      },
      showSelectUser: false,
      selectedUser: [],
      tooltipContent: "1.当执行频次选择每日,执行方法是offSetDaySendMessage,偏移量大于0时,(当前时间[yyyy-mm-dd]-检查类型里的检查时间[yyyy-mm-dd]) % 偏移量 == 0 ,将会推送。\n" +
        "2.当执行方法是generalSendMessage,执行频次是每日时,每天都将会推送。\n " +
        "3.当执行方法是generalSendMessage,执行频次是每周时,偏移量为1将会在每周日触发推送,偏移量为2将会在每周一触发推送。 \n" +
        "4.当执行方法是generalSendMessage，执行频次是每月,偏移量大于0时，将会在每月几号触发推送。偏移量小于0时，将会在每月倒数第几天触发。"
    }
  },
  computed: {
    showUserNames() {
      return this.selectedUser.map(i => i.label).join(',')
    }

  },
  watch: {
    ruleConfigSenderRoleList: {
      handler(val, old) {
        this.form.ruleConfigSenderRole = '';
        this.form.ruleConfigSenderRole = val.map(i => i).join(',')
      }
    }
  },
  created() {
    this.getDicts('rule_config_exec_frequency').then(response => {
      this.ruleConfigExecFrequencyOptions = response.data
    });
    this.getDicts('rule_config_type').then(response => {
      this.ruleConfigTypeOptions = response.data
    });
    this.getDicts('rule_config_exec_func').then(response => {
      this.ruleConfigExecFunctionOptions = response.data
    });
    this.getRoleList();
    this.resetQuery();
  },
  methods: {
    getList() {
      this.loading = true
      listRuleConfig(this.queryParams).then(response => {
        this.ruleConfigList = response.rows;
        this.total = response.total;
        this.loading = false;
      })
    },
    // 执行规则频次名字典翻译
    ruleConfigExecFrequencyFormat(row, column) {
      return this.selectDictLabel(this.ruleConfigExecFrequencyOptions, row.ruleConfigExecFrequency)
    },
    isValidFormat(row, column) {
      return row.isValid ? '有效' : '无效';
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        templateTitle: undefined
      };
      this.getList();
    },
    handleSelectionChange(selection) {
      this.ruleConfigIds = selection.map(item => item.ruleConfigId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    handleAdd() {
      this.reset();
      this.title = '新增规则配置';
      this.open = !!!this.open;
    },
    handleUpdate(row) {
      this.reset();
      const ruleConfigId = row.ruleConfigId || this.ruleConfigIds;
      getRuleConfig(ruleConfigId).then(response => {
        this.form = response.data;
        this.ruleConfigSenderRoleList = undefined;
        if (this.form.ruleConfigSenderRole) {
          this.ruleConfigSenderRoleList = this.form.ruleConfigSenderRole.split(",");
        }
        if (this.form.sysSenderList) {
          this.selectedUser = [];
          this.form.sysSenderList.forEach(item => {
            this.$nextTick(() => {
              this.selectedUser.push({
                label: item.nickName,
                userName: item.userName,
                value: item.fid
              })
            })
          })
        }
        this.open = true;
        this.title = '修改规则配置';
      })
    },
    handleDelete(row) {
      const ruleConfigId = [row.ruleConfigId] || this.ruleConfigIds;
      this.$confirm('是否确认删除规则为"' + row.ruleConfigName + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        let sysRuleConfig = [];
        ruleConfigId.forEach(item => {
          sysRuleConfig.push({"ruleConfigId": item});
        })
        return delRuleConfig(sysRuleConfig)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      }).catch(function () {
      })
    },
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          let tempSysSenderList = [];
          if (this.form.ruleConfigId != undefined) {
            (this.form.sysSenderList || []).forEach(item => {
              tempSysSenderList.push(
                {"ruleConfigId": this.form.ruleConfigId, "userName": item.userName || item}
              )
            })
            this.$delete(this.form, 'sysSenderList')
            this.$set(this.form, 'sysSenderList', tempSysSenderList)
            editRuleConfig(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess('修改成功')
                this.open = false
                this.getList()
              }
            })
          } else {
            this.form.sysSenderList.forEach(item => {
              tempSysSenderList.push(
                {"ruleConfigId": '', "userName": item}
              )
            })
            this.$delete(this.form, 'sysSenderList')
            this.form.sysSenderList = tempSysSenderList;
            saveRuleConfig(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess('新增成功')
                this.open = false
                this.getList()
              }
            })
          }
        }
      })
    },
    reset() {
      this.form = {
        ruleConfigName: undefined,
        ruleConfigType: undefined,
        ruleConfigExecFrequency: undefined,
        ruleConfigThreshold: undefined,
        ruleConfigSenderRole: undefined,
        ruleConfigExecFunction: undefined,
        ruleConfigExecParameter: undefined,
        templateTitle: undefined,
        templateContent: undefined,
        sysSenderList: [],
        isValid: 1,
        isSendNotification: 1,
        execOffset: 0,
        execOffsetField: 'MINUTES'
      }
      this.selectedUser = [];
      this.ruleConfigSenderRoleList = [];
      this.resetForm('form')
    },
    handleView(row) {
      getRuleConfig(row.ruleConfigId).then(response => {
        this.form = response.data;
        this.title = '查看规则配置';
        this.open = !!!this.open;
      })

    },
    getRoleList() {
      listRole({pageSize: 9999}).then((rv) => {
        if (rv.code === 200) {
          this.roleList = rv.rows
        }
      })
    },
    getUserList() {
      listUser(this.userParams).then((rv) => {
        this.userList = rv.rows
      })
    },
    remoteUserMethod(query) {
      if (query != '') {
        this.userParams = {
          pageNum: 1,
          pageSize: 50,
          nickName: query
        }
        listUser(this.userParams).then((rv) => {
          this.userList = rv.rows
        })
      }
    },
    // 选择用户回调
    selectUserCallback(selection) {
      this.selectedUser = selection
      this.form.sysSenderList = selection.map(i => i.userName)
    }
  },
}
</script>

<style scoped>

</style>
